package com.vm.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.vm.commons.VMConst;
import com.vm.model.ActiveSoft;
import com.vm.model.Soft;
import com.vm.myview.ViewUtils;
import com.vm.utils.JsonUtils;
import com.wwt.app.R;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.ScrollView;

public class TopDayFragment extends BaseFragment {

	private View view;
	protected static final String TAG = "TopDayFragment";
	private RequestQueue mQueue;
	private List<Soft> listsofts;
	ImageLoader mImageLoader;
	ImageListener listener;
	ViewUtils viewUtils;
	LinearLayout found_ll_1;

	ScrollView mScrollView;
	boolean canRequest = true;
	String name;
	int pageNow = 1;

	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("CategoryFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.ranking_day, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		mQueue = Volley.newRequestQueue(getActivity());
		viewUtils = new ViewUtils(getActivity());

		init();
		isPrepared = true;
		lazyLoad();

	}

	public void init() {

		found_ll_1 = (LinearLayout) view.findViewById(R.id.found_ll_1);

		mScrollView = (ScrollView) view.findViewById(R.id.scrollview_list);
		mScrollView.setOnTouchListener(new TouchListenerImpl());
	}

	private class TouchListenerImpl implements OnTouchListener {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {

					if (canRequest) {
						canRequest = false;
						System.out.print("canRequest:" + canRequest);
						pageNow += 1;
						System.out.print("pageNow:" + pageNow);
						String url = VMConst.REQUEST_URL
								+ "getByActiveType?typeId=17";

						if (url.contains("?")) {
							url += "&pageNow=" + pageNow;
						} else {
							url += "?pageNow=" + pageNow;
						}

						final String url2 = url;

						JsonArrayRequest searchArrayRequest = new JsonArrayRequest(
								url2, new Listener<JSONArray>() {
									@Override
									public void onResponse(JSONArray arg0) {

										for (int i = 0; i < arg0.length(); i++) {
											try {
												JSONObject jsonObject = arg0
														.getJSONObject(i);

												final ActiveSoft activeSoft = JsonUtils
														.jsonToBean(
																jsonObject,
																ActiveSoft.class);

												// 判断是活动类型还是软件类型
												if (url2.contains("getSoftByType")) {
													System.out
															.println("判断是活动类型还是软件类型");
													activeSoft
															.setSoftId(activeSoft
																	.getId());
													activeSoft.setId(null);
												}

												LinearLayout linearLayout = viewUtils
														.dyAddView(i,
																activeSoft, 1);
												found_ll_1
														.addView(linearLayout);

											} catch (JSONException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
										}
										canRequest = true;

									}

								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										// Log.e(TAG, error.getMessage(),
										// error);
									}
								});

						mQueue.add(searchArrayRequest);

					}

				}
				break;

			default:
				break;
			}
			return false;
		}

	};

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
		Log.i("FoundFragment", "lazyLoad");
		Log.i("lazyLoad", "isPrepared=" + isPrepared + ",isVisible="
				+ isVisible + ",mHasLoadedOnce=" + mHasLoadedOnce);
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}
		Log.i("FoundFragment", "lazyLoad--AsyncTask");
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(1000);
					// 在这里添加调用接口获取数据的代码
					initData();
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功

					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				UIHelper.hideDialogForLoading();
			}
		}.execute();
	}

	public void initData() {
		listsofts = new ArrayList<Soft>();
		String url = VMConst.REQUEST_URL + "getByActiveType?typeId=17";
		JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {
						// arg0.length();

						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								final ActiveSoft activeSoft = JsonUtils
										.jsonToBean(jsonObject,
												ActiveSoft.class);

								found_ll_1.addView(viewUtils.dyAddView(i,
										activeSoft, 1));

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(jsonObjectRequest);
	}

}
